package zone.czh.woi.woim.base.channel.adapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolConfig;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import zone.czh.woi.base.util.Pair;
import zone.czh.woi.protocol.protocol.Payload;

import java.util.ArrayList;
import java.util.List;

/**
*@ClassName: WebSocketAdapter
*@Description: None
*@author woi
*/
@ChannelHandler.Sharable
public class WebSocketAdapter extends ProtocolAdapter<TextWebSocketFrame>{

    ObjectMapper objectMapper = new ObjectMapper();
    public WebSocketAdapter(){
        this("web_socket");
    }
    public WebSocketAdapter(String protocolName){
        super(protocolName);
    }


    @Override
    protected Payload parse(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) {
        Payload payload = null;
        try {
            payload = objectMapper.readValue(textWebSocketFrame.text(), Payload.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        return payload;
    }

    @Override
    public Object encode(ChannelHandlerContext ctx, Payload payload) {
        TextWebSocketFrame data = null;
        try {
            data = new TextWebSocketFrame(objectMapper.writeValueAsString(payload));
        }catch (Exception e){
            e.printStackTrace();
        }
        return data;
    }

    @Override
    public List<Pair<String,ChannelInboundHandler>> getDecoders() {
        List<Pair<String,ChannelInboundHandler>> list = new ArrayList<>();
        list.add(new Pair<String,ChannelInboundHandler>(null,new HttpServerCodec()));
        list.add(new Pair<String,ChannelInboundHandler>(null,new HttpObjectAggregator(65536)));
        WebSocketServerProtocolConfig config = WebSocketServerProtocolConfig.newBuilder()
                .websocketPath("/ws")
                .checkStartsWith(true)
                .maxFramePayloadLength(Integer.MAX_VALUE)
                .build();
        list.add(new Pair<String, ChannelInboundHandler>(null,new WebSocketServerProtocolHandler(config)));
        return list;
    }

    @Override
    public List<Pair<String,ChannelOutboundHandler>> getEncoders() {
        return null;
    }
}
